const express = require("express");
const route = express.Router();
const path = require('path')
const fs = require("fs")
const advModel = require("../db/model/advModel")
const isLoginMiddle = require("../middleware/isLoginMiddle")

route.delete("/deleteAdv", isLoginMiddle, async (req, res) => {
    //从前端获取_id值
    const {
        _id
    } = req.query

    //    console.log(_id);
    //    console.log(req.path);// /deleteAdv
    //    console.log(req.query);//{ _id: '/upload/786f1de48783ea643133a3c00.png' }


    //去数据库中查询对应的数据
    // console.log(advModel.findOne({
    //     _id
    // })
    // );
    try {
        const {
            advHref
        } = await advModel.findOne({
            _id
        })


        // console.log(advHref);
        
        const imgName = advHref.split("/")[2]



        //删除这个图片(在upload文件夹中)
        fs.unlink(path.resolve(__dirname, "../upload", imgName), () => {
            console.log("删除成功");
        })
    } catch (e) {
        console.log("删除图片逻辑有错误"+ e.message);
        return res.send({
            code: 10001,
            msg: "删除图片逻辑有错误" + e.message,
            data: null
        })
    }

    //删除数据库中的数据,根据id值找到数据库中对应的数据并删除,id是前端请求时传过来的数据
    try {
        const deleteResult = await advModel.deleteOne({
            _id
        })

        res.send({
            code: 10000,
            msg: "删除广告列表成功98",
            data: null
        })
    } catch (e) {
        console.log("删除广告列失败" + e.message);
        res.send({
            code: 10001,
            msg: "删除广告列表失败6" + e.message,
            data: null
        })
    }
})

//TypeError('app.use() requires a middleware function')文件没有暴露
module.exports = route
